package com.example.demofdfs.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 删除指定目录的所有文件, 包括目录本身也被删除
 * @author Administrator
 *
 */
public class FileUtil {

	public static void main(String[] args) throws IOException {
//		String file = "tmp-data.txt";
//		read(file);
		files(new File("H:\\development_tools\\bomc\\cps\\ctbomc\\ctbomc-user\\ctbomc-user-server\\target\\generated-test-sourcestarget\\generated-sources\\annotations"));
	}

	public static String read(String filename) throws IOException {
		File file = new File(filename);
		if (!file.exists())
			return null;
		FileInputStream in = new FileInputStream(file);
		byte[] b = new byte[1024];
		int len;
		StringBuilder sb = new StringBuilder();
		while((len = in.read(b)) > -1)
			sb.append(new String(b, 0, len));
		in.close();
		return sb.toString();
	}
	
	public static int count(File filename) throws IOException {
		InputStream inputStream = new FileInputStream(filename);
		byte[] b = new byte[1024];
		int len;
		int size = 0;
		while ((len = inputStream.read(b)) > -1) {
			size += len;
		}
		inputStream.close();
		return size == 0 ? -1 : size;
	}
	
	public static void files(File file) {
		if (file.exists())
			if (file.isFile())
				deleteFile(file);
			else {
				File[] fs = file.listFiles();
				for (File f : fs)
					files(f);
				deleteFile(file);
			}
				
	}
	
	public static void deleteFile(File file) {
		
		if (file.exists())
			if (file.delete())
				System.out.println(file.getPath());
			else 
				System.err.println(file.getPath());
	}
	
	public static void write(String text, String filename) {
		File file = new File(filename);
		OutputStream out = null;
		try {
			out = new FileOutputStream(file, true);
			out.write(text.getBytes());
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
